from django.shortcuts import render
from django.http import HttpResponse
from django.db import connection
import json
from Tools.model_to_python import *
from . import models


#定时任务
from . import schedulers
schedulers.start()


def funds(request):
    '''
    get all funds
    '''
    print(request)
    try:
        funds = queryset_to_list_dict(models.Fund.objects.all())
        for fund in funds:
            fund['manager'] = object_to_dict(models.Manager.objects.get(pk = fund['manager_id']))
            fund['update_script'] = object_to_dict(models.UpdateScript.objects.get(pk = fund['update_script_id']))
            state = None
            states_query_set = models.State.objects.filter(fund_id = fund['id']).order_by('-date')[:1]
            if states_query_set.exists():
                state = states_query_set.first()
            fund['state'] = object_to_dict(state)
            fund['state_id'] = fund['state'].get('id', -1)
            #print(connection.queries)
        res = {
            "code": 200,
            "data": funds
        }
    except Exception as e:
        res = {
            "code": 401,
            "errMsg": str(e)
        }
    return HttpResponse(json.dumps(res), content_type = "application/json")


def manager(request, id):
    '''
    get a manager by id
    '''
    try:
        manager = object_to_dict(models.Manager.objects.get(pk = id))
        res = {
            "code": 200,
            "data": manager
        }
    except Exception as e:
        res = {
            "code": 401,
            "errMsg": str(e)
        }
    return HttpResponse(json.dumps(res), content_type = "application/json")

